﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

using Tradex.Connectivity.ConnectorModel;
using Tradex.Market;

using Tradex.Connectivity.NxCore;

namespace Tradex.Connectivity.NxCore.Test {

    internal class NxCoreTest :
        IConnectorCallback,
        IMarketConnectorCallback 
    {

        public NxCoreTest() {
            _Connector = new NxCoreConnector();
            _Connector.SetCallback((IConnectorCallback)this);
            _Connector.SetCallback((IMarketConnectorCallback)this);
        }

        public void Connect(string connectionString) {
            _Connector.Connect(connectionString);
        }

        public void WaitFinished() {
            while (true) {
                switch (ConnectorStatusCode) {
                    case ConnectionStatusCode.Disconnected:
                    case ConnectionStatusCode.Error:
                        return;
                }
                System.Threading.Thread.Sleep(250);
            }
        }

        NxCoreConnector _Connector = null;
        InstrumentKey _FilterKey = new InstrumentKey("CBOT", "YM.Z10");

        ConnectionStatusCode ConnectorStatusCode { get; set; }
        string ConnectorStatusMessage { get; set; }

        void IConnectorCallback.LogEntry(System.Diagnostics.TraceLevel traceLevel, string subject, string message, string origin, string reference) {
        }

        void IConnectorCallback.StatusUpdate(ConnectionStatusCode status, string message) {
            Console.WriteLine(
                String.Format(CultureInfo.InvariantCulture, "STATUS: {0} {1}", status, message)
            );
            ConnectorStatusCode = status;
            ConnectorStatusMessage = message;
        }

        void IMarketConnectorCallback.Activity(
            Market.InstrumentKey instrumentKey,
            Market.Activity update) 
        {
            if (instrumentKey != _FilterKey) {
                return;
            }

            Console.WriteLine(
                String.Format(CultureInfo.InvariantCulture, "{0}/{1} {2}", instrumentKey.Market, instrumentKey.Instrument, update.ToString())
            );
        }

        void IMarketConnectorCallback.InstrumentUpdate(
            Market.InstrumentKey instrumentKey,
            Market.InstrumentInfo instrumentInfo, Market.InstrumentPricing instrumentPricing)
        {
            if (instrumentKey != _FilterKey) {
                return;
            }

            Console.WriteLine (
                String.Format (CultureInfo.InvariantCulture, "{0}", instrumentKey)
            );
        }
    }
}
